package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone(); //获取手机号
        if(StringUtils.isBlank(phone)){
            return R.error("短信发送失败");
        }
        //生成随机的4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("code={}",code);
        //调用阿里云提供的短信服务API完成发送短信
        //SMSUtils.sendMessage("瑞吉外卖","",phone,code);
        //需要将生成的验证码保存到Session
        session.setAttribute(phone,code);
        return R.success("手机验证码短信发送成功");
    }

    /**
     * 移动端用户登录
     *
     * @param map     map 中至少包含 "phone" 与 "code" 这两个 key
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, Object> map, HttpSession session) {
        log.info("map : {}", map);
        // 获取手机号
        String phone = map.get("phone").toString();
        String codeInput = map.get("code").toString();
        String codeInSession = (String) session.getAttribute(phone);
        // 比对不成功
        if (!(codeInSession != null  && codeInSession.equals(codeInput))){
            return  R.error("验证码错误");
        }
        // 根据手机号查找用户
        LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
        userLQW.eq(User::getPhone, phone);
        User user = userService.getOne(userLQW);
        //判断当前手机号对应的用户是否已经存在
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        // 将 userId 存入 session
        session.setAttribute("userId", user.getId().toString());
        return R.success(user);
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().invalidate(); //清除 Session
        return R.success("退出成功");
    }

}
